package com.hwl.bigfileupload.controller;

import com.hwl.bigfileupload.common.Result;
import com.hwl.bigfileupload.dto.FileChunkDTO;
import com.hwl.bigfileupload.service.UploadTaskService;
import com.hwl.bigfileupload.vo.CheckResultVO;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sentry
 * @since 2023-09-23
 */
@RestController
@RequestMapping("fileStorage")
public class FileStorageController {

    @Resource
    private UploadTaskService uploadTaskService;

    /**
     * 本接口为校验接口，即上传前，先根据本接口查询一下 服务器是否存在该文件
     *
     * @param dto 入参
     * @return vo
     */
    @GetMapping("upload")
    public Result<CheckResultVO> checkUpload(FileChunkDTO dto) {
        return Result.ok(uploadTaskService.checkUpload(dto));
    }

    /**
     * 本接口为实际上传接口
     *
     * @param dto      入参
     * @return boolean
     */
    @PostMapping("upload")
    public Result<Boolean> upload(FileChunkDTO dto, HttpServletRequest request) {
        if (ServletFileUpload.isMultipartContent(request)) {
            if (uploadTaskService.uploadFile(dto)) {
                return Result.ok();
            }
            return Result.error();
        }
        return Result.error("未包含文件上传域");
    }

    /**
     * 下载接口，这里只做了普通的下载
     */
    @GetMapping(value = "/download/{identifier}")
    public void downloadByIdentifier(HttpServletRequest request, HttpServletResponse response, @PathVariable("identifier") String identifier) {
        uploadTaskService.downloadByIdentifier(identifier, request, response);
    }

}
